<?php

//
// +---------------------------------------------------------+
// | 开发组
// +---------------------------------------------------------+
// | Copyrigh  (c)  2020 The PHP Group
// +---------------------------------------------------------+
// | 商户 代理商
// +---------------------------------------------------------+
// | zxc
// | php后端开发
// |
// +———————————————————+
//

namespace App\Models\Api;

use App\Tools\Financial;
use App\Tools\Prstatic;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Log;

class StoreOrderGoods extends Model
{

    protected $table = 'store_order_goods';
    protected $primaryKey = 'id';
    protected $dateFormat = 'U'; // 时间戳

    /**
     * 获取订单商品列表
     */
    public static function getListByOid($order_id, $type = 0)
    {
        $db = self::from('store_order_goods as sg')
            ->select(['sg.goods_number', 'sg.goods_price', 'sg.is_give', 'g.goods_name', 'g.goods_price as goods_price_yu', 'g.goods_img','g.goods_sn','g.goods_specification','g.id as goods_id','g.goods_unit'])
            ->leftJoin('goods as g', 'g.id', '=', 'sg.goods_id')
            ->where(['sg.order_id' => $order_id]);
        if ($type == 1) {
            $db->where(['sg.is_give' => 0]);
        } elseif ($type == 2) {
            $db->where(['sg.is_give' => 1]);
        }
        $list = $db->get()->toArray();
        return $list;
    }

    /**
     * 添加商品
     * @param $orderId
     * @param $data
     * @return mixed
     */
    public static function addInfoByOrderId($orderId, $storeId, $data, $create_user = '')
    {
        $info['order_id'] = $orderId;
        $info['store_id'] = $storeId;
        $info['goods_id'] = $data['goods_id'];
        $info['goods_pid'] = $data['goods_pid'];
        $info['goods_group'] = $data['goods_group'];
        $info['type'] = $data['type'];
        $info['goods_price'] = $data['sale_price'];
        $info['goods_number'] = $data['goods_num'];
        if (empty($data['is_give']) || $data['is_give'] < 1) {
            $info['goods_amount'] = $data['goods_price'] * $data['goods_num'];
        }
        $info['is_give'] = $data['is_give'];
        $info['remark'] = '补货';
        $info['created_at'] = time();
        $info['create_user'] = $create_user;
        $info['store_product_batch'] = date('Y-m-d'); // 添加商品批次号
        
        // 添加goods_group_pid字段处理逻辑
        if (isset($data['goods_group_pid'])) {
            $info['goods_group_pid'] = $data['goods_group_pid'];
        }
        
        Log::info('添加商品', $info);
        // 返回插入记录的id
        return self::insertGetId(array_filter($info));
    }
}